package com.atgugu.flink.chapter07.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer.Semantic.EXACTLY_ONCE;

/**
 * @Author lzc
 * @Date 2022/4/6 10:02
 */
public class Flink10_Kafka_Flink_Kafka {
    public static void main(String[] args) throws Exception {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env.enableCheckpointing(3000); // 开启checkpoint: 状态会进行远程的存储
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/ck10");
        
        // 设置checkpoint的超时时间
        env.getCheckpointConfig().setCheckpointTimeout(30 * 1000);
        // 设置最多执行几个版本的checkpoint
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        // 设置checkpoint的一致性
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        // 两个不同版本的checkpoint的最小间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        // 当job取消的时候, checkpoint继续保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(RETAIN_ON_CANCELLATION);
        //        env.getCheckpointConfig().enableExternalizedCheckpoints();
        
        //
        Properties sourceProps = new Properties();
        sourceProps.put("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092");
        sourceProps.put("group.id", "atguigu2");
        // 如果没有上次的消费记录, 则从最新消费, 如果有上次消费记录, 则从上次的位置开始消费
        sourceProps.put("auto.reset.offset", "latest");
        
        Properties sinkProps = new Properties();
        sinkProps.put("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092");
        sinkProps.put("transaction.timeout.ms", 15 * 60 * 1000);
    
    
        SingleOutputStreamOperator<Tuple2<String, Long>> stram = env
            .addSource(new FlinkKafkaConsumer<String>("t1", new SimpleStringSchema(), sourceProps))
            .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                @Override
                public void flatMap(String line,
                                    Collector<Tuple2<String, Long>> out) throws Exception {
                    for (String word : line.split(" ")) {
                        out.collect(Tuple2.of(word, 1L));
                    
                    }
                }
            })
            .keyBy(t -> t.f0)
            .sum(1);
        
        stram
            .addSink(new FlinkKafkaProducer<Tuple2<String, Long>>(
                          "default",
                          new KafkaSerializationSchema<Tuple2<String, Long>>() {
                              @Override
                              public ProducerRecord<byte[], byte[]> serialize(Tuple2<String, Long> element,
                                                                              @Nullable Long timestamp) {
                                  byte[] value = (element.f0 + "_" + element.f1).getBytes(StandardCharsets.UTF_8);
                                  return new ProducerRecord<>("t2", value);
                              }
                          },
                          sinkProps,
                          EXACTLY_ONCE
                      )
        );
        
        stram.addSink(new SinkFunction<Tuple2<String, Long>>() {
            @Override
            public void invoke(Tuple2<String, Long> value, Context context) throws Exception {
                if (value.f0.contains("x")) {
                    
                    throw new RuntimeException("故意抛出一个异常....");
                }
            }
        });
    
    
        env.execute();
    }
    
}
